package com.yanqu.client.message;

import com.yanqu.road.define.YanQuMessageDefine;
import com.yanqu.road.message.YanQuMessage;
import io.netty.buffer.ByteBuf;
import io.vertx.core.buffer.Buffer;
public class Decrypt {
    public YanQuMessage decodeYanquMessage(Buffer in) {
        ByteBuf inByteBuf = in.getByteBuf();
        if (inByteBuf.readableBytes() < YanQuMessageDefine.HEADER_SIZE) {
            return null;
        }
        ByteBuf byteBuf = inByteBuf.slice();

        short headerMark = byteBuf.readShort();
        if (headerMark != YanQuMessageDefine.HEADER_MARK) {
            byteBuf.readShort();
            return null;
        }
        int msgLength = byteBuf.readInt();
        if (msgLength > inByteBuf.readableBytes()) {
            return null;
        }
        if (msgLength <= 0) {

            return null;
        }
        return decrypt(inByteBuf, msgLength);
    }

    protected YanQuMessage decrypt(ByteBuf in, int msgLength) {
        int bodyLen = msgLength - YanQuMessageDefine.HEADER_SIZE;

        YanQuMessage yanQuMessage = new YanQuMessage();
        yanQuMessage.readHeaderNetty(in);
        if (bodyLen > 0) {
            byte[] bytes = new byte[bodyLen];
            in.readBytes(bytes, 0, bodyLen);
            yanQuMessage.setBytes(bytes);
            return yanQuMessage;
        } else {
            yanQuMessage.setBytes(new byte[0]);
            return yanQuMessage;
        }
    }
}
